#include "server.h"

// 初始化socket: 用来三次握手socket
int init_server(ServerInfo *server_info, config_info info){

    server_info->exit_flag = 0;
    memset(&server_info->queue, 0,  sizeof(queue_t));
    pthread_mutex_init(&server_info->clients_mutex, NULL);  // 初始化客户端互斥锁
    memset(server_info->clients, 0, sizeof(server_info->clients));  // 清空客户端信息数组
    pthread_cond_init(&server_info->cond , NULL);

    server_info->server_socket = socket(AF_INET, SOCK_STREAM, 0);
    server_info->client_count = 0;  // 初始化客户端计数为0

    int reuse = 1;
    setsockopt(server_info->server_socket, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));

    struct sockaddr_in sockaddr;
    sockaddr.sin_family = AF_INET;
    sockaddr.sin_port = htons(atoi(info.port));
    sockaddr.sin_addr.s_addr = inet_addr(info.ip);
    bind(server_info->server_socket , (struct sockaddr *)&sockaddr, sizeof(sockaddr));

    listen(server_info->server_socket, 10 );

    server_info->thread_ids = (pthread_t *)calloc(sizeof(pthread_t), info.thread_num);

    // 启动子线程
    for(int i=0; i<info.thread_num; i++){
        pthread_create(&server_info->thread_ids[i], NULL, client_thread,(void *)server_info);
    } 

    return 0;
}



